import axios from 'axios'
import store from '@/store'
import router from '@/router'

import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  async config => {
    if (store.getters.token) {
      // console.log(config)
      // 新增员工不能带token，所以这里需要判断如果请求路径是新增员工的，就要把请求的token去掉
      // 或者在每个不需要token的请求参数中添加一个变量，变量设置为true，就可以直接判断
      if (config.url !== '/auth/local/register') {
        config.headers.Authorization = 'Bearer ' + store.getters.token
      } else {
        config.headers.Authorization = ''
      }
    } else {
      // console.log(1)
      router.push('/')
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(response => {
  // console.log(response)
  if (response.config.url !== '/api/auth/local' && response.config.method === 'post' || response.config.method === 'POST') {
    console.log(response)
    Message.success('添加成功')
  }
  if (response.config.method === 'put' || response.config.method === 'PUT') {
    Message.success('编辑成功')
  }
  if (response.config.method === 'delete' || response.config.method === 'DELETE') {
    Message.success('删除成功')
  }
  // 对响应数据做点什么
  return response
}, error => {
  // console.log(error.response.status)
  // 对响应错误做点什么
  // return Promise.reject(error)
  if (error.response.status === 401 || error.response.status === 403) {
    localStorage.removeItem('token')
    router.push('/')
  }
})

export default service
